package com.infodms.dms.actions.sales.marketmanage.planissued;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.common.FileUploadManager;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.marketmanage.planissued.ActivitiesPlanIssuedDao;
import com.infodms.dms.dao.sales.marketmanage.planmanage.ActivitiesPlanManageDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanManageDao;
import com.infodms.dms.dao.sales.planmanage.SpacePlanReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmDealerOrgRelationPO;
import com.infodms.dms.po.TtCampaignExecuteChkPO;
import com.infodms.dms.po.TtCampaignExecutePO;
import com.infodms.dms.po.TtCampaignPO;
import com.infodms.dms.po.TtCampaignPoseChkRPO;
import com.infodms.dms.po.TtCampaignSpaceExecutePO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

public class ActivitiesExeAnnexUpload {
	public Logger logger = Logger.getLogger(ActivitiesExeAnnexUpload.class);   
	ActivitiesPlanIssuedDao dao  = ActivitiesPlanIssuedDao.getInstance();
	ActivitiesPlanManageDao managedao  = ActivitiesPlanManageDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	
	private final String ANNEX_UPLOAD_URL = "/jsp/sales/marketmanage/planissued/activitiesExeAnnexUpload.jsp";
	private final String DETAIL_URL = "/jsp/sales/marketmanage/planissued/activitiesExeAnnexUploadDetail.jsp";
	
	public void activitiesAnnexUploadInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			act.setOutData("areaList", areaList);
			System.out.println(ANNEX_UPLOAD_URL+"----------");
			
			act.setForword(ANNEX_UPLOAD_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案附件上传页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void activitiesQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			Long poseId  = logonUser.getPoseId();
			TtCampaignPoseChkRPO tcpcrp = new TtCampaignPoseChkRPO();
			tcpcrp.setPoseId(poseId);			
			List list = dao.select(tcpcrp);
			if(!CommonUtils.isNullList(list)){
				tcpcrp = (TtCampaignPoseChkRPO)dao.select(tcpcrp).get(0);
			}else {
				throw new RuntimeException("您没有下发权限，请联系系统管理员！");
			}
			
			String areaId=request.getParamValue("areaId");
			String campaignNo = request.getParamValue("campaignNo");
			String campaignName = request.getParamValue("campaignName");
			String campaignSubject = request.getParamValue("campaignSubject");
			String dealerCode = request.getParamValue("dealerCode");
			String startDate = CommonUtils.checkNull(request.getParamValue("startDate")) ;
			String endDate = CommonUtils.checkNull(request.getParamValue("endDate")) ;
			
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.activitiesPlanOemCheckQuery(startDate, endDate, poseId, areaId,campaignNo, campaignName, campaignSubject, dealerCode, Constant.CAMPAIGN_CHECK_STATUS_19.toString(), curPage,Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		}catch(RuntimeException e) {
			logger.error(e) ;
			act.setException(e) ;
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 活动执行方案审批明细查询
	 */
	public void activitiesDetail(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String campaignId = request.getParamValue("campaignId");
			String executeId = request.getParamValue("executeId");
			String camType =request.getParamValue("camType") ;
			 /* 
			  * 新增
			  * 总部用户登陆时可看广告费用，总部市场推广费用、区域可用市场推广费用、经销商可用市场推广费用
			  * */
			TtCampaignPO mypo1=new TtCampaignPO();
			mypo1.setCampaignId(Long.parseLong(campaignId));
			TtCampaignPO mypo2=new TtCampaignPO();
			mypo2=(TtCampaignPO) dao.select(mypo1).get(0);
			String areaId=String.valueOf(mypo2.getAreaId());
			StringBuffer group_id = new StringBuffer();
			StringBuffer group_code = new StringBuffer();
			List<Map<String,String>> actList = managedao.queryActiveVehicleType(campaignId);
			if (null != actList && actList.size()>0) {
				for (int i = 0; i < actList.size(); i++) {
					group_id.append(String.valueOf(actList.get(i).get("GROUP_ID"))).append(",");
					group_code.append(String.valueOf(actList.get(i).get("GROUP_CODE"))).append(",");
				}
			}
			group_id.deleteCharAt(group_id.length()-1);
			group_code.deleteCharAt(group_code.length()-1);
			
			Map<String, Object> map3 = dao.activitiesTargetQuery(executeId);
			
			List<Map<String, Object>> list3 = dao.getCheckInfo(executeId);
			List<Map<String, Object>> list4 = dao.getAttachInfo(campaignId);
			
			Long orgId=logonUser.getOrgId();
			List<Map<String, Object>> amountList4 = dao.queryAreaOem2Cost(areaId, orgId);//总部广告费用
			List<Map<String, Object>> amountList5 = dao.queryAreaOemCost(areaId, orgId);//总部市场推广费用
			
			Map<String, Object> map2 = null ;
			List<Map<String, Object>> list1 = null ;
			List<Map<String, Object>> list2 = null ;
			
			if(!camType.equals(Constant.CAMPAIGN_TYPE_03.toString())) {
				map2 = dao.activitiesInfoQuery(campaignId, executeId,"111");
				String dealer_id="";
				if(map2.get("DEALER_ID")!=null&&map2.get("DEALER_ID")!=""){
					dealer_id = map2.get("DEALER_ID").toString();
				}
				
				TmDealerOrgRelationPO tdo = dao.getAreaOrgIdByDealerId(dealer_id);
				//获取区域组织id
				String area_org_id = "";
				if(tdo!=null && tdo.getOrgId()!=null) area_org_id = tdo.getOrgId().toString();
				String oem_org_id = logonUser.getCompanyId().toString();
				
				
	//			List<Map<String, Object>> list1 = dao.getActivitiesCostbyId(executeId, campaignId);
	//			List<Map<String, Object>> list2 = dao.getActivitiesMediaCost(executeId);
				list1 = dao.getActivitiesCostbyId(executeId, campaignId,dealer_id,area_org_id,areaId,oem_org_id);
				list2 = dao.getActivitiesMediaCost(executeId,dealer_id,area_org_id,areaId,oem_org_id);
				
				List<Map<String, Object>> amountList1 = dao.queryDealerCost(dealer_id, areaId);
				
				List<Map<String, Object>> amountList2 = dao.queryAreaCost(dealer_id,areaId);
				
				if(amountList1.size()>0){
					if(amountList1.get(0).get("AVAILABLE_AMOUNT")==null||amountList1.get(0).get("AVAILABLE_AMOUNT")==""){
						act.setOutData("amountList1", 0);
					}else{
						act.setOutData("amountList1", amountList1.get(0).get("AVAILABLE_AMOUNT"));
					}
				}else{
					act.setOutData("amountList1", 0);
				}
				if(amountList2.size()>0){
					if(amountList2.get(0).get("AVAILABLE_AMOUNT")==null||amountList2.get(0).get("AVAILABLE_AMOUNT")==""){
						act.setOutData("amountList2", 0);
					}else{
						act.setOutData("amountList2", amountList2.get(0).get("AVAILABLE_AMOUNT"));
					}
				}else{
					act.setOutData("amountList2", 0);
				}
			} else {
				TtCampaignSpaceExecutePO oldTcse = new TtCampaignSpaceExecutePO() ;
				oldTcse.setSpaceId(Long.parseLong(executeId)) ;
				TtCampaignSpaceExecutePO tcse = (TtCampaignSpaceExecutePO)dao.select(oldTcse).get(0) ;
				String areaOrgId = tcse.getOrgId().toString() ;
				map2 = dao.activitiesInfoQuery(campaignId, executeId, Long.parseLong(areaOrgId));
				
				List<Map<String, Object>> executePlans = SpacePlanManageDao.getInstance().getMyExecutePlanByCmpId(campaignId);
				
				list1 = ActivitiesPlanManageDao.getInstance().getActivitiesCostbyId(executeId, campaignId);
				list2 = SpacePlanReportDao.getActivitiesMediaCost(executeId);
				
				String amountList1 = "0" ;
				String amountList2 = SpacePlanReportDao.getCost(Long.parseLong(areaOrgId), areaId, Constant.COST_TYPE_02) ;
				
				act.setOutData("amountList1", amountList1);
				act.setOutData("amountList2", amountList2);
				act.setOutData("executePlans", executePlans) ;
			}
			
			if(amountList4.size()>0){
				if(amountList4.get(0).get("AVAILABLE_AMOUNT")==null||amountList4.get(0).get("AVAILABLE_AMOUNT")==""){
					act.setOutData("amountList4", 0);
				}else{
					act.setOutData("amountList4", amountList4.get(0).get("AVAILABLE_AMOUNT"));
				}
				}
			else{
				act.setOutData("amountList4",0);
			}
			if(amountList5.size()>0){
				if(amountList5.get(0).get("AVAILABLE_AMOUNT")==null||amountList5.get(0).get("AVAILABLE_AMOUNT")==""){
					act.setOutData("amountList5", 0);
				}else{
					act.setOutData("amountList5", amountList5.get(0).get("AVAILABLE_AMOUNT"));
				}
			}else{
				act.setOutData("amountList5",0);
			}
						
			Map<String,Integer> mapA = new HashMap<String, Integer> () ;
			mapA.put("DEALER", Constant.COST_TYPE_01) ;
			mapA.put("AREA", Constant.COST_TYPE_02) ;
			mapA.put("OEM1", Constant.COST_TYPE_03) ;
			mapA.put("OEM2", Constant.COST_TYPE_04) ;
			
			Map<String,Integer> mapC = new HashMap<String, Integer> () ;
			mapC.put("cy03", Constant.CAMPAIGN_TYPE_03) ;
			
			String type = "" ;
			if(list1.size()>0&&list1.get(0).get("ITEM_COUNT")!=null){
				type = list1.get(0).get("COST_TYPE").toString() ;
			}
			if(list2.size()>0&&list2.get(0).get("ITEM_COUNT")!=null){
				type = list2.get(0).get("COST_TYPE").toString() ;
			}
			act.setOutData("type", type) ;
						
			act.setOutData("camType", camType) ;
			act.setOutData("mapA", mapA) ;
			act.setOutData("mapC", mapC) ;
			act.setOutData("group_id", group_id.toString());
			act.setOutData("group_code", group_code.toString());
			act.setOutData("areaId", areaId);
			act.setOutData("list1", list1);
			act.setOutData("list2", list2);
			act.setOutData("list3", list3);
			act.setOutData("list4", list4);
			act.setOutData("map2", map2);
			act.setOutData("map3", map3);
			act.setForword(DETAIL_URL);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 活动执行方案下发执行
	 */
	public void activitiesConfirm(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String camType = request.getParamValue("camType") ;
			ActivitiesCostOpera aco = new ActivitiesCostOpera() ;
			
			String executeId = request.getParamValue("executeId");
			String checkDesc = request.getParamValue("checkDesc");
			String []fjids = request.getParamValues("fjids");
			
			if (camType.equals(Constant.CAMPAIGN_TYPE_03.toString())) {
				String campaignId = request.getParamValue("campaignId") ;
				
				TtCampaignSpaceExecutePO tcse1 = new TtCampaignSpaceExecutePO() ;
				tcse1.setSpaceId(Long.parseLong(executeId)) ;
				
				TtCampaignSpaceExecutePO tcse2 = new TtCampaignSpaceExecutePO() ;
				
				tcse2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_06);
				
				tcse2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcse2.setUpdateBy(logonUser.getUserId());
				
				dao.update(tcse1, tcse2);
				
				TtCampaignExecuteChkPO tcecp = new TtCampaignExecuteChkPO() ;
				
				String checkId = SequenceManager.getSequence("");
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				tcecp.setCheckPositionId(logonUser.getPoseId());
				tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_03);
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//添加附件
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
				act.setOutData("returnValue", 1);
				
				TtCampaignExecutePO tcep1 = new TtCampaignExecutePO();
				tcep1.setCampaignId(Long.parseLong(campaignId)) ;
				
				TtCampaignExecutePO tcep2 = new TtCampaignExecutePO();
				
				tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_06);
				tcep2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcep2.setUpdateBy(logonUser.getUserId());
				
				Integer updateLen = dao.update(tcep1, tcep2);
				
				if(updateLen > 0) {
					List<Map<String, Object>> campaignList = dao.select(tcep1) ;
					
					TtCampaignExecutePO tce = null ;
					for(int i=0; i<updateLen; i++) {
						tce = (TtCampaignExecutePO)campaignList.get(i) ;
						executeId = tce.getExecuteId().toString() ;
						
						tcecp = new TtCampaignExecuteChkPO() ;
						
						checkId =SequenceManager.getSequence("");
						tcecp.setCheckId(Long.parseLong(checkId));
						tcecp.setExecuteId(Long.parseLong(executeId));
						tcecp.setCheckOrgId(logonUser.getOrgId());
						tcecp.setCheckDate(new Date(System.currentTimeMillis()));
						tcecp.setCheckDesc(checkDesc);
						tcecp.setCheckPositionId(logonUser.getPoseId());
						tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_03);
						tcecp.setCheckUserId(logonUser.getUserId());
						tcecp.setCreateBy(logonUser.getUserId());
						tcecp.setCreateDate(new Date(System.currentTimeMillis()));
						dao.insert(tcecp);
						
						//添加附件
						FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
						act.setOutData("returnValue", 1);
					}
				}
			} else {
				TtCampaignExecutePO tcep1 = new TtCampaignExecutePO();
				TtCampaignExecutePO tcep2 = new TtCampaignExecutePO();
				TtCampaignExecuteChkPO tcecp = new TtCampaignExecuteChkPO();
				
				tcep1.setExecuteId(Long.parseLong(executeId));
				
				tcep2.setCheckStatus(Constant.CAMPAIGN_CHECK_STATUS_06);
				tcep2.setUpdateDate(new Date(System.currentTimeMillis()));
				tcep2.setUpdateBy(logonUser.getUserId());
				dao.update(tcep1, tcep2);
				
				String checkId =SequenceManager.getSequence("");
				tcecp.setCheckId(Long.parseLong(checkId));
				tcecp.setExecuteId(Long.parseLong(executeId));
				tcecp.setCheckOrgId(logonUser.getOrgId());
				tcecp.setCheckDate(new Date(System.currentTimeMillis()));
				tcecp.setCheckDesc(checkDesc);
				tcecp.setCheckPositionId(logonUser.getPoseId());
				tcecp.setCheckStatus(Constant.MARKET_CHECK_STATUS_03);
				tcecp.setCheckUserId(logonUser.getUserId());
				tcecp.setCreateBy(logonUser.getUserId());
				tcecp.setCreateDate(new Date(System.currentTimeMillis()));
				dao.insert(tcecp);
				
				//添加附件
				FileUploadManager.fileUploadByBusiness(checkId, fjids, logonUser);
				act.setOutData("returnValue", 1);
			}
		}catch(RuntimeException e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,e.getMessage());
			logger.error(logonUser,e1);
			act.setException(e);
		}
		catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"活动执行方案审批提交");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
}
